<?php

namespace backend\modules\admin\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\behaviors\TimestampBehavior;
use backend\modules\admin\models\Role;
/**
 * This is the model class for table "category".
 *
 * @property string $username
 * @property string $password
 * @property string $userid
 * @property string $roleid
 * @property int $lastloginip
 * @property string $lastlogintime
 * @property string $realname
 * @property string $del
 */
class Admin extends ActiveRecord
{
    
     /**
     * admin类关联数据库表名称 admin
     */
    public static function tableName()
    {
        return '{{%admin}}';
    }
    
    /**
    * 验证规则
    */
    public function rules()
    {
        return [
            ['username','unique','message' => '管理员名不能重复'],            
            [['username','password','roleid'],'required','message'=>'不能为空'],
            ['username','match','pattern'=>'/^[a-zA-Z]\w{4,14}$/','message'=>'只能以字母开头且只能是字母数字或下划线,长度为5——15位'],
            ['password','match','pattern'=>'/^\w{4,32}$/','message'=>'长度为5——33位'],
            ['realname','string'], 
            ['lastloginip','match','pattern'=>'/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/'],
            [['roleid','lastlogintime'],'number'],
            [['tel','city_id','area_id','department_id','isAccept'],'default','value'=>''],
        ];
    }

    /**
     * 属性标签
     */
    public function attributeLabels()
    {
        return [
            'username' => '管理员名', 
            'password' => '密码',
            'roleid'=>'所属角色',
            'lastloginip' => '最后登录IP',
            'lastlogintime' => '最后登录时间',
            'realname'=>'真实姓名',
            'city_id'=>'城市',
            'area_id'=>'区县',
            'department_id'=>'部门',
            'tel'=>'电话',
            'isAccept'=>'是否办理人员'
        ];
    }

    /**
     * beforesave, 将密码用MD5加密
     */
    public function beforeSave($insert)
    {
        if($insert)
        {
            //密码不为空的话进行MD5加密
            if(!empty($this->password))
            $this->password = md5($this->password);
            else
            unset($this->password); //如果是插入得 可以进行一些操作以及赋值
        }
        return parent::beforeSave($insert);
    }

    /** 
    * @inheritdoc 
    */ 
    public static function findIdentity($id) 
    { 
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]); 
    } 
    
    /**
    * Finds user by username 
    * 
    * @param string $username 
    * @return static|null 
    */ 
    //查询在admin表中是否存在此username，若存在就返回一个username的实例
    public static function findByUsername($username) 
    {
        $admin = Admin::find()
        ->where(['username' => $username])
        ->asArray()
        ->one();
        if($admin)
        {
            return new static($admin);
        }
        return null; 
    } 
    /**
     * 获取当前管理员Role
     */
    public  function getRole() 
    {
           $role = Role::findOne($this->roleid);
         
           if($role)
           {
               return $role;
           }
           return null; 
    } 
       
    
    /**
     * 获得管理员id
     */
    public function getId() 
    { 
        return $this->userid;
    }

    /**
    * Validates password
    *
    * @param string $password password to validate
    * @return bool if password provided is valid for current user
    */
    //判断验证重复密码
    public function validatePassword($password)
    {
        return $this->password === $password;
    }

    /**
     * 获取登陆ip和登陆时间
     */
    public function getIpTime($username)
    {
        
        $datetime = new \DateTime();
        $user = self::find()->where(['username'=>$username])->one();
        $user->lastloginip=$_SERVER["REMOTE_ADDR"];
        $user->lastlogintime=$datetime->format('U');
        if($user->save())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}